package org.jetnuke.modules.blog;

import org.apache.log4j.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;

public class Resources implements IAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(Resources.class);

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - start"); //$NON-NLS-1$
		}

		if (ui == null || ui.getID() < 2)
			return null;
		String initPath = SystemGlobals
				.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR)
				+ "/blog/" + ui.getID() + "/";
		File pathDir = new File(initPath);
		if (!pathDir.exists()) {
			pathDir.mkdirs();
		}

		List ls = null;
		File files[] = pathDir.listFiles();
		ls = new ArrayList();
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				if (!files[i].isDirectory())
					ls.add(files[i]);
			}
		}

		Iterator it = ls.iterator();
		ArrayList list = new ArrayList();
		while (it.hasNext()) {
			File file = (File) it.next();
			List intList = new ArrayList();
			intList.add(file.getName());
			intList.add(new Long(file.length()));
			list.add(intList);
		}
		vc.put("ls", list);
		vc.put("uid", new Integer(ui.getID()));
		ActionForward returnActionForward = new ActionForward(op, info);
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
		}
		return returnActionForward;
	}

}
